package com.dq.service.sys.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.dq.context.Constant;
import com.dq.controller.in.RechargeCardRequest;
import com.dq.controller.in.UserCardQuery;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.domain.base.AbstractEntity;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.org.Org;
import com.dq.domain.service.ServiceProject;
import com.dq.domain.sys.user.Account;
import com.dq.domain.sys.user.user.BossUser;
import com.dq.domain.sys.user.user.WxUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.domain.sys.user.user.centre.UserCard;
import com.dq.domain.sys.user.user.centre.UserCardServiceProjectCentre;
import com.dq.exception.customException.AdminException;
import com.dq.repository.BaseRepositories;
import com.dq.service.sys.user.UserCardService;
import com.dq.vo.Vo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author luchangtong
 * @Date 2020/4/14 9:17
 */
@Service
public class UserCardServiceImpl extends BaseRepositories implements UserCardService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Vo addCard(RechargeCardRequest rechargeCardRequest) throws AdminException {
        initObject(rechargeCardRequest);
        UserCard userCard = new UserCard();
        WxUser wxUser = dao.get(WxUser.class, rechargeCardRequest.getWxUserId());
        if (wxUser == null) {
            throw new AdminException("用户信息异常");
        }
        if (userCardRepository.findByDeletedFalseAndWxUser(wxUser).size() == 0) {
            wxUser.setOpenCardTime(System.currentTimeMillis());
            wxUserRepository.save(wxUser);
        }
        Org org = dao.get(Org.class, rechargeCardRequest.getOrgId());
        if (org == null) {
            throw new AdminException("所选门店异常");
        }
        userCard.setCardNo(AbstractEntity.generyDatetimeAndRandomNum(Constant.ORDERS_SUFF_COUNT));
        userCard.setWxUser(wxUser);
        userCard.setOrg(org);
        userCard.setStatus(UserCard.Status.on);
        userCard.setPrice(BigDecimal.ZERO);
        userCard.setGivePrice(BigDecimal.ZERO);
        userCard.setCardType(rechargeCardRequest.getCardType());
        if (rechargeCardRequest.getStaffUserId() != null) {
            SysUser sysUser = dao.get(SysUser.class, rechargeCardRequest.getStaffUserId());
            if (sysUser != null) {
                userCard.setCreateUser(dao.get(SysUser.class, rechargeCardRequest.getStaffUserId()));
            }
        }
        UserCard save = userCardRepository.save(userCard);
        if (rechargeCardRequest.getFlag() == 1) {
            ServiceProject serviceProject = dao.get(ServiceProject.class, rechargeCardRequest.getServiceProjectId());
            UserCardServiceProjectCentre userCardServiceProjectCentre = new UserCardServiceProjectCentre();
            userCardServiceProjectCentre.setUserCard(save);
            userCardServiceProjectCentre.setServiceProject(serviceProject);
            userCardServiceProjectCentre.setCount(0L);
            userCardServiceProjectCentre.setGiveCount(0L);
            userCardServiceProjectCentreRepository.save(userCardServiceProjectCentre);
        }
        return new Vo(HttpStatus.OK);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Vo editCard(RechargeCardRequest rechargeCardRequest) throws AdminException {
        initObject(rechargeCardRequest);
        UserCard userCard = dao.get(UserCard.class, rechargeCardRequest.getId());
        if (userCard == null) {
            throw new AdminException("会员卡异常");
        }
        if (rechargeCardRequest.getStaffUserId() != null) {
            BossUser staffUser = dao.get(BossUser.class, rechargeCardRequest.getStaffUserId());
            if (staffUser == null) {
                throw new AdminException("员工异常");
            }
        }
        Org org = dao.get(Org.class, rechargeCardRequest.getOrgId());
        if (org == null) {
            throw new AdminException("门店异常");
        }
        userCard.setOrg(org);
        userCard.setPrice(rechargeCardRequest.getPrice());
        userCard.setGivePrice(rechargeCardRequest.getGivePrice());
        if (rechargeCardRequest.getFlag() == 0) {
            if (userCard.getPrice().compareTo(rechargeCardRequest.getPrice()) != 0) {
                Account account = new Account();
                account.setUserCard(userCard);
                account.setUser(userCard.getWxUser());
                account.setSysDept(org);
                if (rechargeCardRequest.getStaffUserId() != null) {
                    BossUser bossUser = dao.get(BossUser.class, rechargeCardRequest.getStaffUserId());
                    if (bossUser != null) {
                        account.setStaffUser(bossUser);
                    }
                }
                if (userCard.getPrice().compareTo(rechargeCardRequest.getPrice()) == -1) {
                    account.setChangeType(Account.ChangeType.add);
                    account.setPrice(rechargeCardRequest.getPrice().subtract(userCard.getPrice()));
                } else {
                    account.setChangeType(Account.ChangeType.less);
                    account.setPrice(userCard.getPrice().subtract(rechargeCardRequest.getPrice()));
                }
                account.setGivePrice(rechargeCardRequest.getGivePrice());
                account.setAccountChangeType(Account.AccountChangeType.recharge);
                account.setAccountPayType(Account.AccountPayType.online);
                account.setRechargeType(rechargeCardRequest.getRechargeType());
                account.setStatus(Account.Status.normal);
                accountRepository.save(account);
            }
        } else {
            ServiceProject serviceProject = dao.get(ServiceProject.class, rechargeCardRequest.getServiceProjectId());
            if (serviceProject == null) {
                throw new AdminException("服务项目异常");
            }
            UserCardServiceProjectCentre userCardServiceProjectCentre = userCardServiceProjectCentreRepository.findByDeletedFalseAndUserCardAndServiceProject(userCard, serviceProject);
            userCardServiceProjectCentre.setCount(rechargeCardRequest.getCount());
            userCardServiceProjectCentre.setGiveCount(rechargeCardRequest.getGiveCount());
            userCardServiceProjectCentreRepository.save(userCardServiceProjectCentre);
        }
        return new Vo(HttpStatus.OK);
    }

    public void initObject(RechargeCardRequest rechargeCardRequest) throws AdminException {
        if (rechargeCardRequest.getFlag() == 1) {
            if (rechargeCardRequest.getServiceProjectId() == null) {
                throw new AdminException("服务项目异常");
            }
        }
    }

    @Override
    public Vo editStatus(Long id) throws AdminException {
        UserCard userCard = dao.get(UserCard.class, id);
        if (userCard == null) {
            throw new AdminException("找不到会员卡");
        }
        if (userCard.getStatus().toString().equals(UserCard.Status.on.toString())) {
            userCard.setStatus(UserCard.Status.off);
        } else {
            userCard.setStatus(UserCard.Status.on);
        }
        userCardRepository.save(userCard);
        return new Vo(HttpStatus.OK);
    }

    @Override
    public List<UserCard> cardList(UserCardQuery userCardQuery) throws AdminException {

        userCardQuery.format();

        Map<String, Object> query = createQuery(userCardQuery);

        return dao.find(dao.query2Hql(UserCard.class, query), query);
    }

    @Override
    public Long cardCount(UserCardQuery userCardQuery) throws AdminException {
        userCardQuery.format();
        Map<String, Object> query = createQuery(userCardQuery);

        return dao.count(dao.count2Hql(UserCard.class, query), query);
    }

    @Override
    public List<UserCard> cardByUser(Long wxUserId) throws AdminException {
        WxUser wxUser = dao.get(WxUser.class, wxUserId);
        if (wxUser == null) {
            throw new AdminException("微信用户异常");
        }
        List<UserCard> userCardList = userCardRepository.findByDeletedFalseAndWxUser(wxUser);
        return userCardList;
    }

    @Override
    public List<UserCard.Vo> transformUserCard(List<UserCard> list) throws AdminException {
        List<UserCard.Vo> toList = new ArrayList<>();
        if (list.size() > 0) {
            list.forEach(userCard -> {
                UserCard.Vo userCardVo = (UserCard.Vo) userCard.toVO();
                if (userCard.getCardType().toString().equals(UserCard.CardType.two.toString())) {
                    List<JSONObject> serviceProjectList = new ArrayList<>();
                    List<UserCardServiceProjectCentre> centreList = userCardServiceProjectCentreRepository.findByDeletedFalseAndUserCard(userCard);
                    for (UserCardServiceProjectCentre centre : centreList) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", centre.getId());
                        jsonObject.put("count", centre.getCount());
                        jsonObject.put("giveCount", centre.getGiveCount());
                        jsonObject.put("serviceProjectId", centre.getServiceProject().getId());
                        jsonObject.put("serviceProjectName", centre.getServiceProject().getProjectName());
                        serviceProjectList.add(jsonObject);
                    }
                    userCardVo.setServiceProjectList(serviceProjectList);
                }
                toList.add(userCardVo);
            });
        }
        return toList;
    }

    public Map<String, Object> createQuery(UserCardQuery userCardQuery) throws AdminException {
        //测试
        //userCardQuery.setOrgId(0L);
        Map<String, Object> query = userCardQuery.parseMap();
        if (StringUtils.isNotEmpty(userCardQuery.getCardNo())) {
            query.put("cardNo" + BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(userCardQuery.getCardNo()));
            query.remove("cardNo");
        }
        if (StringUtils.isNotEmpty(userCardQuery.getWxUserRealcName())) {
            query.put("wxUser_userRealcName" + BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(userCardQuery.getWxUserRealcName()));
            query.remove("wxUserRealcName");
        }
        if (userCardQuery.getOrgId() != null && userCardQuery.getOrgId() != 0) {
            query.put("org_id", userCardQuery.getOrgId());
            query.remove("orgId");
        }
        if (userCardQuery.getOrgId() != null && userCardQuery.getOrgId() == 0) {
            query.remove("orgId");
        }
        if (userCardQuery.getBeginTime() != null) {
            query.put("createTime" + BaseDaoImpl.gteSqlStr, userCardQuery.getBeginTime());
            query.remove("beginTime");
        }
        if (userCardQuery.getEndTime() != null) {
            query.put("createTime" + BaseDaoImpl.lteSqlStr, userCardQuery.getEndTime());
            query.remove("endTime");
        }
        return query;
    }
}
